<template>
  <div class="container">
    <template>
      <div v-if="mode === 'edit'">
        <div>
          <van-uploader
            @delete="handleRemove"
            @click-preview="handleImgPreview"
            v-model="imgFileList"
            :max-count="limitCount"
            :preview-full-image="false"
            :disabled="disabled"
          />
        </div>
        <van-image-preview
          v-model="showPreviewImg"
          :images="previewImages"
          :show-index="false"
          closeable
        >
        </van-image-preview>
        <van-button
          class="recognize-btn"
          type="primary"
          @click="recognizeRequest"
          :disabled="recognizeDisabled"
          :loading="recognizeLoading"
          loading-text="识别中..."
        >
          {{ btnText }}
        </van-button>
        <van-row v-if="recognizeResult">
          <van-col :span="24">
            <div
              v-html="recognizeResult"
              class="recognize-result"
            ></div>
          </van-col>
        </van-row>
      </div>
      <div v-else>{{ value }}</div>
    </template>
  </div>
</template>

<script>
import customRequest from "../../mixins/custom-request.js"
import axios from "axios"
import CryptoJS from "crypto-js"
import { Toast } from "vant";
export default {
  name: "textRecognize",
  components: {},
  mixins: [customRequest],
  props: {
    value: {},
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // url: {
    //   type: String,
    //   default: "",
    // },
    // token: {
    //   type: String,
    //   default: "",
    // },
    // paasid: {
    //   type: String,
    //   default: "",
    // },
    // trackId: {
    //   type: String,
    //   default: "",
    // },
    // category: {
    //   type: String,
    //   default: "doc",
    // },
  },
  data() {
    return {
      btnText: "文本识别",
      imgFileList: [],
      previewImages: [],
      limitCount: 1,
      showPreviewImg: false,
      recognizeLoading: false,
      recognizeResult: null,
      belong: '文本识别'
    };
  },

  watch: {},
  mounted() {
    if (this.value) {
      if (this.mode == "view") {
        this.disabled = true;
      }
    }
  },
  computed: {
    imgFileLength() {
      return _.get(this.imgFileList, "length", 0)
    },
    recognizeDisabled() {
      return this.disabled || this.imgFileLength <= 0;
    },
  },
  methods: {
    handleRemove(file) {
      this.disabled = false
      this.recognizeResult = null
    },
    handleImgPreview(file) {
      const { content } = file
      this.previewImages.push(content)
      this.showPreviewImg = true;
    },
    recognizeRequest() {
      if (this.imgFileLength <= 0) return
      this.recognizeLoading = true;
      const url = this.getCodeValueByCode('TEXT_RECOGNIZE_URL')
      const token = this.getCodeValueByCode('TEXT_RECOGNIZE_TOKEN')
      const paasid = this.getCodeValueByCode('TEXT_RECOGNIZE_PAASID')
      const trackId = this.getCodeValueByCode('TEXT_RECOGNIZE_TRACK_ID')
      const category = this.getCodeValueByCode('TEXT_RECOGNIZE_CATEGORY')
      const requestUrl = `${this.preurl}api/afc/integration/recognize`
      const headers = this.header
      const timestamp = (Date.now() / 1000).toFixed();
      const nonce = Math.random().toString(36).substring(2);
      // const { url, token, paasid, trackId, category } = this;
      const signature = CryptoJS.SHA256(timestamp + token + nonce + timestamp).toString(CryptoJS.enc.Hex).toUpperCase();
      const payload = { url, token, paasid, trackId, category, timestamp, nonce, signature };
      const formData = new FormData();
      const blobData = new Blob([JSON.stringify(payload)], { type: 'application/json' });
      formData.append("recognizeMap", blobData);
      for (let item of this.imgFileList) {
        const { file } = item;
        formData.append("picFile", file);
      }
      axios.post(`${requestUrl}`, formData, { headers }).then((resp) => {
        this.recognizeResult = resp.data
        this.disabled = true
      }).catch((err) => {
        console.log("请求接口错误:", err)
        const message = _.get(err, "response.data.errorLocalizedMessage")
        Toast.fail(message || err.message)
      }).finally(() => {
        this.recognizeLoading = false;
      })
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
}
.recognize-btn {
  margin: 10px 0;
}
.recognize-result {
  text-align: justify;
}
</style>
